﻿using d1Common.Interface;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Web.Http.Routing;

namespace d1Common.WebController
{
    public class Authorize2Attribute : FilterAttribute, IAuthenticationFilter
    {
        public Authorize2Attribute()
        {

        }
        private const string AccessTokenName = "accessToken";

        //支持OAuth Authorsize,get 参数，cookie三种方式认证
        public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
        {
            Authorize2Controller _controller = context.ActionContext.ControllerContext.Controller as Authorize2Controller;
            if (_controller == null) throw new UserException("只允许应用于Authorize2ControllerBase");

            string _token;
            if (context.ActionContext.Request.Headers.Authorization != null)
            {
                if (context.ActionContext.Request.Headers.Authorization.Scheme.ToLower() != "bearer")
                {
#if Dev
                    _token = "testTokenValue";
                    _controller.Token = _token;
                    _controller.UserId = "admin";
                    _controller.UserName = "系统管理员";
                    return Task.FromResult<object>(null);
#endif
                    throw new UserException("只支持Bearer方式的用户认证");
                }
                _token = context.ActionContext.Request.Headers.Authorization.Parameter;
            }
            else
            {
                var value = context.Request.GetQueryNameValuePairs().FirstOrDefault(u => u.Key == AccessTokenName);
                if (value.Value != null)
                {
                    _token = value.Value.ToString();
                }
                else
                {
                    var cookie = context.Request.Headers.GetCookies(AccessTokenName);
                    if (cookie == null || cookie.Count <= 0 || cookie[0].Cookies.Count <= 0)
                    {
#if Dev
                        _token = "testTokenValue";
                        _controller.Token = _token;
                        _controller.UserId = "admin";
                        _controller.UserName = "系统管理员";
                        return Task.FromResult<object>(null);
#endif
                        throw new UserException("需要登录认证", HttpStatusCode.Unauthorized);
                    }
                    _token = cookie[0].Cookies[0].Value;
                }
            }
            IToken _tokenEntity = doServices.Instance.Do4AService.GetToken2(_token);
            if (_tokenEntity == null)
            {
#if Dev
                _token = "testTokenValue";
                _controller.Token = _token;
                _controller.UserId = "admin";
                _controller.UserName = "系统管理员";
                return Task.FromResult<object>(null);
#endif
                throw new UserException("未通过用户身份认证.", HttpStatusCode.Unauthorized);
            }
            _controller.Token = _token;
            _controller.UserId = _tokenEntity.UserId;
            _controller.UserName = _tokenEntity.UserName;

            return Task.FromResult<object>(null);
        }

        public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
        {
            return Task.FromResult<object>(null);
        }


    }
}